package com.weight.netty;

 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.*;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.weight.WeightmgApplication;

import java.net.InetSocketAddress;
 
 @Component
 @Slf4j
 public class NettyServer { 
     private EventLoopGroup master;
     private EventLoopGroup slaver;
     private ServerBootstrap serverBootstrap;
     private ChannelFuture channelFuture;
     
     public NettyServer(){
         master= new NioEventLoopGroup();
         slaver= new NioEventLoopGroup();
         serverBootstrap =new ServerBootstrap(); 
         serverBootstrap.group(master,slaver)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ServerInitializer());
     }
     /**
  		* 启动netty服务
      * @throws InterruptedException
      */ 
     private static class SingletionNettyServer {
         static  final NettyServer instance = new NettyServer();
     }

     public static NettyServer getInstance(){
         return  SingletionNettyServer.instance;
     }
     public void start(){
         this.channelFuture= serverBootstrap.bind(8083);
         System.err.println("netty 启动完毕");
     }
     
     /**
      	* 销毁
      */
     public static void main(String[] args) throws Exception{
         EventLoopGroup master= new NioEventLoopGroup();
         EventLoopGroup slaver= new NioEventLoopGroup();
         try {
             ServerBootstrap serverBootstrap =new ServerBootstrap();
             serverBootstrap.group(master,slaver)
                     .channel(NioServerSocketChannel.class)
                     .childHandler(new ServerInitializer());
             ChannelFuture channelFuture= serverBootstrap.bind(8081).sync();
             channelFuture.channel().closeFuture().sync();
         }finally {
             // 关闭线程
             master.shutdownGracefully();
             slaver.shutdownGracefully();
         }
     }
     
 }